package cn.edu.sdjzu.xg.bysj.dao;

import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisor;
import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisorEntry;
import util.JdbcHelper;

import java.sql.*;
import java.util.Collection;

public class ApplicationForSupervisorDao {
    private static ApplicationForSupervisorDao applicationForSupervisorDao = null;

    private ApplicationForSupervisorDao(){}

    public static ApplicationForSupervisorDao getInstance(){
        if (applicationForSupervisorDao == null){
            applicationForSupervisorDao = new ApplicationForSupervisorDao();
        }
        return applicationForSupervisorDao;
    }

    public boolean add(ApplicationForSupervisor afs,
                       Connection connection)
            throws SQLException {
        boolean added = false;
        String addAfsr_sql = "INSERT INTO applicationForSupervisor" +
                "(selfIntroduction,student_id,year) VALUES (?,?,?)";

        PreparedStatement pstmt = connection.prepareStatement(addAfsr_sql,
                Statement.RETURN_GENERATED_KEYS);

        pstmt.setString(1,afs.getSelfIntroduction());
        pstmt.setInt(2,afs.getStudent().getId());
        pstmt.setInt(3,afs.getYear());
        pstmt.executeUpdate();
        ResultSet resultSet = pstmt.getGeneratedKeys();
        int afs_id = 0;
        if (resultSet.next()){
            afs_id = resultSet.getInt(1);
        }
        JdbcHelper.close(resultSet,pstmt);

        Collection<ApplicationForSupervisorEntry> afses =
                afs.getApplicationForSupervisorEntries();
        for ( ApplicationForSupervisorEntry as:afses) {
            String addAFSE_sql = "INSERT INTO applicationForSupervisorEntry" +
                    "(teacher_id,priority,applicationForSupervisor_id) VALUES (?,?,?)";
            PreparedStatement pstmt2 = connection.prepareStatement(addAFSE_sql);
            pstmt2.setInt(1,as.getTeacher().getId());
            pstmt2.setInt(2,as.getPriority());
            pstmt2.setInt(3,afs_id);
            added = pstmt2.executeUpdate()>0;
            JdbcHelper.close(null,pstmt2);
        }
        return added;
    }
}